

use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use crate::base::{Result,Error};
use crate::structs::{FieldProps, OrderItems, WhereCauses};


#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct ListProps {
    #[serde(default = "pk_col_default")]
    pub pk_col: String,
    /** 表格每页显示的行数 */
    #[serde(default = "page_size_default")]
    pub page_size: u16,
    /** 是否可以多选*/
    #[serde(default)]
    pub multi_select: bool,
    /** 表格的初始排序 */
    #[serde(default)]
    pub init_sorter: Option<OrderItems>,
    /** 表格数据的查询条件 */
    #[serde(default)]
    pub seeks: Option<WhereCauses>,
    /** 是否是表格编辑模式 */
    #[serde(default)]
    pub is_table_edit: bool,
    #[serde(default)]
    pub footer_show_props: TableFooterShowProps,
}
fn pk_col_default() -> String {
    "".to_string()
}
fn page_size_default() -> u16 {
    20
}
#[cfg(feature = "ssr")]
impl ListProps {
    pub fn parse(&mut self, fps: &Vec<FieldProps>, table_name: &str) -> Result<()> {
        if let Some(ss) = &self.init_sorter {
            for oi in ss.as_ref().iter() {
                oi.parse(fps, table_name)?;
            }
        }
        if let Some(ss) = &self.seeks {
            for wc in ss.as_ref().iter() {
                wc.parse(fps, table_name)?;
            }
        }
        for fp in fps.iter() {
            if fp.is_pk {
                if self.pk_col.is_empty() {
                    self.pk_col = fp.name.to_owned();
                } else {
                    if self.pk_col != fp.name {
                        // 主键冲突
                        return Err(Error::from(format!(
                            "表{}的主键字段{}和配置字段{}不一致",
                            table_name, self.pk_col, fp.name
                        )));
                    }
                    if !fp.is_auto_incr {
                        // 主键不是自增
                        return Err(Error::from(format!(
                            "表{}的主键字段{}不是自增",
                            table_name, self.pk_col
                        )));
                    }
                }
                break;
            }
        }
        Ok(())
    }
}


///表格页脚的属性
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct TableFooterShowProps{
    ///能否翻页
    pub can_page: bool,
    ///能否选择每页显示的行数
    pub can_page_size: bool,
    ///能否选择列头
    pub can_sel_cols: bool,
    ///能否排序和筛选
    pub can_order_filter: bool,
}
impl TableFooterShowProps {
    pub fn new(can_page: bool, can_page_size: bool, can_sel_cols: bool, can_order_filter: bool) -> Self {
        Self {
            can_page,
            can_page_size,
            can_sel_cols,
            can_order_filter,
        }
    }
}
impl Default for TableFooterShowProps {
    fn default() -> Self {
        Self::new(true, true, true, true)
    }
}
